package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.mall.dto.ClearCartItemResponse;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.api.ProductApi;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;


@Slf4j
@Component
public class ClearCartItemHandler extends AbstractTransHandler {

    @Autowired
    ProductApi productApi;

    // 删除购物车商品，调用商品服务

    // 是否采用异步方式执行
    @Override
    public boolean isAsync() {
        return false;
    }

    /**
     * 订单完成后调用服务清空指定用户的购物车的指定商品
     *
     * @param context 带有请求数据的对象
     * @return boolean
     * @author Chen_Feng
     * @since 2022/07/09 15:08
     */
    @Override
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        // 封装一个请求，调用服务清除指定userId的购物车中的指定商品
        ClearCartItemRequest clearCartItemRequest = new ClearCartItemRequest();
        clearCartItemRequest.setProductIds(createOrderContext.getBuyProductIds());
        clearCartItemRequest.setUserId(createOrderContext.getUserId());
        ClearCartItemResponse clearCartItemResponse = productApi.clearCartItemByUserID(clearCartItemRequest);

        // 如果返回的状态码不是成功，则抛出异常
        if (!Objects.equals(clearCartItemResponse.getCode(), SysRetCodeConstants.SUCCESS.getCode())) {
            throw new BizException(clearCartItemResponse.getCode(), clearCartItemResponse.getMsg());
        }
        return true;
    }
}
